package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"role-guard/cache"
	"role-guard/models"
	"role-guard/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login_error_" + username
	loginCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if loginCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if loginCount >= 2 {
			models.DB.Where("username=?", username).Find(&user)
			marshal, _ := json.Marshal(user)
			cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*3)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁三小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func Add(c *gin.Context) {
	id := c.PostForm("id")
	rola := c.PostForm("rola")
	user := models.User{
		Rola: rola,
	}
	tx := models.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "添加失败",
			})
			return
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	err := models.DB.Where("id=?", id).Create(&user).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	err = tx.Commit().Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var user []models.User
	err := models.DB.Offset(offset).Limit(size).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redise_key := "list_"
	models.DB.Find(&user)
	cache.Rdb.Get(cache.Ctx, redise_key)
	marshal, _ := json.Marshal(user)
	cache.Rdb.Set(cache.Ctx, redise_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
